package com.icore.bean;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.icore.AppException;

public class GoucheList extends BaseEntity {

	ArrayList<Gouche> list;

	public ArrayList<Gouche> getList() {
		return list;
	}

	public void setList(ArrayList<Gouche> list) {
		this.list = list;
	}

	public static GoucheList parse(InputStream stream) throws AppException {
		GoucheList goucheList = new GoucheList();

		try {
			String res = readByByte(stream, -1, new ByteArrayOutputStream(1024));
			if (res != null && res.length() > 0) {
				try {
					JSONObject resObj = new JSONObject(res);
					int code = resObj.getInt("code");
					goucheList.setResCode(code);
					// 失败:{code:0,description:数据库语句异常,认证失败}
					if (code == 0) {
						goucheList.setResMessage(resObj.getString("description"));
					}
					/*
					 * 成功:{"description":"查询成功",
					 * "data":[{"create_date":"2013/08/11","state":"1","customer_name":"李铭晟","car_no":"20131218A001"},
					 * {"create_date":"2013/08/11","state":"1","customer_name":"黄鹏举","car_no":"20131218A002"}], "code":1}
					 */
					else if (code == 1) {
						goucheList.setResMessage(resObj.getString("description"));

						ArrayList<Gouche> list = new ArrayList<Gouche>();
						String dataStr = resObj.getString("data");
						JSONArray dataArr = new JSONArray(dataStr);
						for (int i = 0; i < dataArr.length(); i++) {
							Gouche gouche = new Gouche();

							JSONObject dataObj = (JSONObject) dataArr.get(i);
							gouche.setCreateData(dataObj.getString("create_date"));
							gouche.setState(dataObj.getString("state"));
							gouche.setCustomerName(dataObj.getString("customer_name"));
							gouche.setCarNo(dataObj.getString("car_no"));

							list.add(gouche);
						}
						goucheList.setList(list);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		} catch (AppException e) {
			e.printStackTrace();
			throw AppException.io(e);
		}
		return goucheList;
	}
}
